import java.awt.event.*;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.swing.*;
import net.miginfocom.swing.*;

public class Book_Borrowing extends JFrame {
    private JButton button2;
    private JLabel label1;
    private JLabel label2;
    private JTextField textField1;
    private JLabel label3;
    private JTextField textField2;
    private JLabel label4;
    private JSpinner spinner1;
    private JButton button1;

    public Book_Borrowing() {
        initComponents();
    }

    private void button2MouseClicked(MouseEvent e) {
        this.dispose();
        user_Home u = new user_Home();
        u.setVisible(true);
    }

    private void button1MouseClicked(MouseEvent e) {
        String bookId = textField1.getText().trim();
        String bookName = textField2.getText().trim();

        // 获取JSpinner的值并转换为Date
        Date date = (Date) spinner1.getValue();
        // 使用Calendar提取年、月、日
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1; // 月份从0开始，所以加1
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        // 将年、月、日转换为字符串
        String formattedDate = year + "-" + String.format("%02d", month) + "-" + String.format("%02d", day); // 格式化为"yyyy-MM-dd"

        // 数据库连接参数
        String url = "jdbc:mysql://localhost:3306/javaproject?useSSL=false&serverTimezone=UTC";
        String username = "root";
        String password = "root";

        // 查询SQL语句
        String querySql = "SELECT * FROM book_information WHERE book_id = ? AND book_title = ?";

        // 验证输入
        if (bookId.isEmpty() || bookName.isEmpty()) {
            JOptionPane.showMessageDialog(this, "书籍ID和书籍名称不能为空", "输入错误",
                    JOptionPane.ERROR_MESSAGE);
            return;
        }

        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            conn = DriverManager.getConnection(url, username, password);

            // 先查询图书是否存在
            pstmt = conn.prepareStatement(querySql);
            pstmt.setString(1, bookId);
            pstmt.setString(2, bookName);
            rs = pstmt.executeQuery();

            if (rs.next()) {
                // 如果存在，则执行借阅操作
                String insertSql = "INSERT INTO book_returning_record_mix " +
                        "(book_id, book_title, user_ID, borrow_time, return_time, if_return) VALUES (?, ?, ?, ?, ?, ?)";

                pstmt = conn.prepareStatement(insertSql);
                pstmt.setString(1, bookId);
                pstmt.setString(2, bookName);
                pstmt.setString(3, Lgoin_user.userid);
                pstmt.setString(4, formattedDate);
                pstmt.setString(5, "null");
                pstmt.setInt(6, 0);

                int rowsAffected = pstmt.executeUpdate();
                if (rowsAffected > 0) {
                    JOptionPane.showMessageDialog(Book_Borrowing.this,
                            "借阅记录添加成功", "成功", JOptionPane.INFORMATION_MESSAGE);
                } else {
                    JOptionPane.showMessageDialog(Book_Borrowing.this,
                            "借阅记录添加失败", "失败", JOptionPane.ERROR_MESSAGE);
                }
            } else {
                JOptionPane.showMessageDialog(Book_Borrowing.this,
                        "图书不存在，请检查输入的书籍ID和书名", "错误", JOptionPane.ERROR_MESSAGE);
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(Book_Borrowing.this,
                    "数据库错误: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        } finally {
            // 关闭资源
            try {
                if (rs != null) rs.close();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            try {
                if (pstmt != null) pstmt.close();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            try {
                if (conn != null) conn.close();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
    }

    private void initComponents() {
        // JFormDesigner - Component initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents  @formatter:off
        button2 = new JButton();
        label1 = new JLabel();
        label2 = new JLabel();
        textField1 = new JTextField();
        label3 = new JLabel();
        textField2 = new JTextField();
        label4 = new JLabel();
        spinner1 = new JSpinner();
        button1 = new JButton();

        //======== this ========
        var contentPane = getContentPane();
        contentPane.setLayout(new MigLayout(
                "hidemode 3",
                // columns
                "[fill]" +
                        "[fill]" +
                        "[fill]" +
                        "[fill]" +
                        "[fill]" +
                        "[fill]" +
                        "[fill]" +
                        "[fill]",
                // rows
                "[]" +
                        "[]" +
                        "[]" +
                        "[]" +
                        "[]" +
                        "[]" +
                        "[]" +
                        "[]" +
                        "[]"));

        //---- button2 ----
        button2.setText("\u8fd4\u56de");
        button2.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                button2MouseClicked(e);
            }
        });
        contentPane.add(button2, "cell 1 0");

        //---- label1 ----
        label1.setText("\u501f\u9605\u56fe\u4e66");
        label1.setFont(label1.getFont().deriveFont(label1.getFont().getSize() + 7f));
        contentPane.add(label1, "cell 3 0");

        //---- label2 ----
        label2.setText("\u56fe\u4e66\u7f16\u53f7\uff1a");
        contentPane.add(label2, "cell 2 2");
        contentPane.add(textField1, "cell 3 2 5 1");

        //---- label3 ----
        label3.setText("\u4e66\u540d\uff1a");
        contentPane.add(label3, "cell 2 4");
        contentPane.add(textField2, "cell 3 4 5 1");

        //---- label4 ----
        label4.setText("\u501f\u9605\u65e5\u671f\uff1a");
        contentPane.add(label4, "cell 2 6");

        //---- spinner1 ----
        spinner1.setModel(new SpinnerDateModel(new java.util.Date(1735539000000L), null, null, java.util.Calendar.DAY_OF_MONTH));
        contentPane.add(spinner1, "cell 3 6 5 1");

        //---- button1 ----
        button1.setText("\u786e\u5b9a");
        button1.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                button1MouseClicked(e);
            }
        });
        contentPane.add(button1, "cell 3 8");
        pack();
        setLocationRelativeTo(getOwner());
        // JFormDesigner - End of component initialization  //GEN-END:initComponents  @formatter:on
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            Book_Borrowing frame = new Book_Borrowing();
            frame.setTitle("图书借阅");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
        });
    }
}